package com.lightboat.config;
 
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
 
// @Configuration
public class StringWebConfig implements WebMvcConfigurer {
 
    @Autowired
    private HttpMessageConverters httpMessageConverters;
 
    /**
     * MappingJackson2HttpMessageConverter 实现了HttpMessageConverter 接口，
     * httpMessageConverters.getConverters() 返回的对象里包含了MappingJackson2HttpMessageConverter
     * @return
     */
    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        return new MappingJackson2HttpMessageConverter(new JacksonMapper());
    }
 
 
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // converters.addAll(httpMessageConverters.getConverters());

        // 添加默认的 StringHttpMessageConverter
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        // 配置 FastJsonHttpMessageConverter
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        List<MediaType> supportMediaTypeList = new ArrayList<>();
        supportMediaTypeList.add(MediaType.APPLICATION_JSON);
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        // 开启引用检测，枚举支持
        config.setWriterFeatures(
                JSONWriter.Feature.WriteEnumUsingToString,
                JSONWriter.Feature.ReferenceDetection,
                JSONWriter.Feature.WriteLongAsString,  // Long 转 字符串
                JSONWriter.Feature.WriteBigDecimalAsPlain   // BigDecimal转为普通数字
        );
        fastJsonConverter.setFastJsonConfig(config);
        fastJsonConverter.setSupportedMediaTypes(supportMediaTypeList);
        fastJsonConverter.setDefaultCharset(StandardCharsets.UTF_8);
        // 将 FastJsonHttpMessageConverter 添加到列表末尾
        converters.add(fastJsonConverter);
        MappingJackson2HttpMessageConverter jackson2Converter = new MappingJackson2HttpMessageConverter();
        jackson2Converter.setObjectMapper(new JacksonMapper());
        converters.add(jackson2Converter);
    }
 
}